package com.kfm.servlet;


import com.kfm.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // download?file=xxxx&download=true
        String file = req.getParameter("file");
        String download = req.getParameter("download");
        if (download != null){
            // 以附件形式下载
            resp.setHeader("content-Disposition", "attachment");
        }

        String path = Constant.UPLOAD_PATH + File.separator + file;

        try(FileInputStream fileInputStream = new FileInputStream(path);){
            // 响应字节内容
            fileInputStream.transferTo(resp.getOutputStream());
        } catch (IOException ex){
            resp.setContentType("text/plain;charset=utf-8");
            resp.getWriter().println("未找到文件");
        }


    }
}
